$ = jQuery

pad = (value, length) ->
    result = value.toString()
    result = '0' + result while result.length < length
    result

getDate = ->
    now = new Date()
    now.setDate now.getDate() - 2
    pad(now.getUTCFullYear(), 4) + '-' + pad(now.getUTCMonth() + 1, 2) + '-' + pad(now.getUTCDate(), 2)

$.fn.feedburner = (options) ->

    settings = $.extend {}, options

    @each ->

        link = $ @
        date = getDate()

        endpoint = "http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=#{link.attr 'href'}&dates=#{date}"

        callback = (response) ->
            readersCount = (response.documentElement.getElementsByTagName 'entry')[0].getAttribute 'circulation'
            link.attr 'title', "#{readersCount} readers"

        $.get settings.url, url: endpoint, callback, 'xml'